<template>
  <eip-modal :visible="visible" :title="title" @close="cancel" :width="800">
    <template slot="body">
      <a-form-model
        ref="form"
        :model="form"
        :rules="rules"
        :label-col="config.labelCol"
        :wrapper-col="config.wrapperCol"
      >
        <a-form-model-item label="名称" prop="name">
          <a-input v-model="form.name" placeholder="请输入名称" allow-clear />
        </a-form-model-item>
        <a-form-model-item label="备注" prop="remark">
          <a-input v-model="form.remark" placeholder="请输入备注" allow-clear />
        </a-form-model-item>
        <a-form-model-item label="类型" prop="style">
          <a-select default-value="primary" allow-clear v-model="form.style">
            <a-select-option value="primary">主按钮 </a-select-option>
            <a-select-option value=""> 次按钮 </a-select-option>
            <a-select-option value="dashed"> 虚线按钮 </a-select-option>
            <a-select-option value="danger"> 危险按钮 </a-select-option>
            <a-select-option value="link"> 链接按钮 </a-select-option>
            <a-select-option value="upload"> 上传按钮 </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="图标" prop="icon">
          <eip-icon
            :name="form.icon"
            :theme="form.theme"
            @click="iconClick"
            @clear="iconClear"
          ></eip-icon>
        </a-form-model-item>
        <a-form-model-item label="动作" prop="action">
          <a-radio-group v-model="form.action" @change="actionChange">
            <a-radio :value="1">执行工作流 </a-radio>
            <a-radio :value="2">填写表单字段 </a-radio>
          </a-radio-group>
          <div
            class="filterTextCon createCon"
            v-if="
              form.action == eipZeroCodeFormSettingButtonAction.workflow &&
              form.submitAfterAutomationConfig.name == null
            "
          >
            <div class="txtFilter Gray">添加按钮后自动创建流程</div>
            <div class="txtFilter Gray">数据源</div>
            <a-radio-group v-model="form.source">
              <a-radio :value="1">可空 </a-radio>
              <a-radio :value="2">一条 </a-radio>
              <a-radio :value="3">多条 </a-radio>
            </a-radio-group>
          </div>
          <div
            class="filterTextCon"
            v-if="
              form.submitAfterAutomationConfig.name &&
              form.action == eipZeroCodeFormSettingButtonAction.workflow
            "
          >
            <div class="txtFilter">
              <div class="Bold">
                {{ form.submitAfterAutomationConfig.name
                }}<span class="margin-left" style="color: red">{{
                  automationDesigner.isFreeze ? "未启用" : ""
                }}</span>
              </div>
              <div class="flexRow Bold">
                <span class="Gray_75">数据源:</span
                ><span class="mLeft3">{{ convertSource(form.source) }}</span>
              </div>
            </div>
            <a-icon type="edit" @click="automationDesignerClick" />
          </div>
          <div
            class="filterTextCon"
            v-if="form.action == eipZeroCodeFormSettingButtonAction.form"
          >
            <div class="txtFilter">
              <div
                v-if="
                  form.form.target == eipZeroCodeFormSettingButtonFormTarget.now
                "
              >
                在当前记录
              </div>
              <div
                v-if="
                  form.form.target ==
                  eipZeroCodeFormSettingButtonFormTarget.correlation
                "
              >
                在关联记录
                <span class="margin-right"></span>
                <span class="Bold WordBreak">“{{ formCorrelationName }}“</span>
              </div>
              <span class="margin-right"
                >中{{
                  form.form.write == eipZeroCodeFormSettingButtonFormWrite.field
                    ? "填写"
                    : "新建"
                }}</span
              ><span class="Bold WordBreak">{{ formFieldRemark }}</span>
            </div>
            <a-icon type="edit" @click="formClick" />
          </div>
        </a-form-model-item>

        <a-form-model-item
          :label="
            form.action == eipZeroCodeFormSettingButtonAction.workflow
              ? '点击按钮时'
              : '提交时'
          "
          prop="designer"
        >
          <div>
            <a-checkbox v-model="form.submit.confirm" @change="submitChange"
              >需要二次确认/填写备注</a-checkbox
            >
            <div class="filterTextCon" v-if="form.submit.confirm">
              <div class="txtFilter">
                <span class="titleTxt Gray">提示文字</span
                ><span class="Gray margin-left Bold">{{
                  form.submit.title
                }}</span>

                <br />
                <span class="titleTxt Gray" v-if="form.submit.content"
                  >详细内容</span
                ><span
                  class="Gray margin-left Bold"
                  v-if="form.submit.content"
                  >{{ form.submit.content }}</span
                >
              </div>
              <a-icon type="edit" @click="submitForm.visible = true" />
            </div>
          </div>
          <div>
            <a-checkbox v-model="form.submit.password"
              >登录密码验证<a-tooltip
                title="启用后，用户需要输入登录密码通过校验后才可执行自定义按钮"
                ><a-icon type="question-circle" /></a-tooltip
            ></a-checkbox>
          </div>
        </a-form-model-item>
        <a-form-model-item
          label="提交后"
          prop="source"
          v-if="form.action == eipZeroCodeFormSettingButtonAction.form"
        >
          <a-checkbox v-model="form.submitAfterAutomation"
            >继续执行工作流<a-tooltip
              title="启用后，用户需要输入登录密码通过校验后才可执行自定义按钮"
              ><a-icon type="question-circle" /></a-tooltip
          ></a-checkbox>
          <div class="filterTextCon" v-if="form.submitAfterAutomation">
            <div class="txtFilter">
              <div class="Bold">
                {{ form.submitAfterAutomationConfig.name
                }}<span class="margin-left" style="color: red">{{
                  automationDesigner.isFreeze ? "未启用" : ""
                }}</span>
              </div>
              <div class="flexRow Bold">
                <span>数据源:</span><span>单条记录</span>
              </div>
            </div>
            <a-icon type="edit" @click="automationDesignerClick" />
          </div>
        </a-form-model-item>
        <a-form-model-item label="启用按钮" prop="enable">
          <a-radio-group v-model="form.enable">
            <a-radio :value="1">一直 </a-radio>
            <a-radio :value="2">满足筛选条件 </a-radio>
          </a-radio-group>
          <div class="euOtrQ" v-if="form.enable == 2">
            <div class="txtFilter fieldEditTxtFilter">
              <div class="filterGroup">
                <span class="spliceText">当</span>
                <div class="flexBox">
                  <span style="flex-shrink: 0; max-width: 100%">客户编号</span
                  ><span class="Gray">等于</span
                  ><span class="breakAll">嗡嗡嗡</span>
                </div>
              </div>
              <div class="filterGroup">
                <span class="spliceText">且</span>
                <div class="flexBox">
                  <span style="flex-shrink: 0; max-width: 100%">客户分类</span
                  ><span class="Gray">是其中一个</span
                  ><span class="breakAll">战略合作,成交客户</span>
                </div>
              </div>
            </div>
            <div class="editFilter"><a-icon type="edit"></a-icon></div>
          </div>
        </a-form-model-item>
      </a-form-model>

      <button-form
        ref="button-form"
        :options="form.form"
        :zeroCodeId="zeroCodeId"
        v-if="buttonForm.visible"
        :visible.sync="buttonForm.visible"
        @ok="formOk"
      ></button-form>

      <button-submit
        ref="button-submit"
        :options="form.submit"
        v-if="submitForm.visible"
        :visible.sync="submitForm.visible"
        @ok="submitOk"
      ></button-submit>

      <automation-designer
        v-if="automationDesigner.visible"
        :visible.sync="automationDesigner.visible"
        :title="automationDesigner.title"
        :configId="automationDesigner.configId"
        @public="automationDesingerPublic"
      ></automation-designer>
    </template>
    <template slot="footer">
      <div class="flex justify-between align-center">
        <div></div>
        <a-space>
          <a-button @click="cancel"><a-icon type="close" />关闭</a-button>
          <a-button @click="ok" key="submit" type="primary"
            ><a-icon type="save" />提交</a-button
          >
        </a-space>
      </div>
    </template>
  </eip-modal>
</template>

<script>
import automationDesigner from "@/pages/system/zerocode/automation/designer";
import buttonForm from "./form";
import buttonSubmit from "./submit";
import { newGuid } from "@/utils/util";
import {
  findById,
  findAutomationById,
} from "@/services/system/zerocode/run/edit";

import { saveAutomation } from "@/services/system/zerocode/components/button/index";
export default {
  name: "edit",
  components: {
    buttonForm,
    buttonSubmit,
    automationDesigner,
  },
  data() {
    return {
      automationDesigner: {
        name: "",
        isFreeze: false,
        visible: false,
        configId: "",
        title: "",
        bodyStyle: {
          padding: "0",
        },
      },

      buttonForm: {
        visible: false,
      },
      submitForm: {
        visible: false,
      },
      config: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
      },
      form: {
        id: newGuid(),
        name: null, //名称
        style: "primary", //样式
        icon: null, //图标
        action: 1, //执行动作，1执行自动化，2填写表单字段
        source: 1, //数据源0无，1单条，2多条
        form: {
          target: 1, //填写对象1当前记录，2关联记录(单条)
          targetCorrelationKey: null, //2关联记录(单条)-关联字段
          write: 1, //指定填写字段1指定填写字段，2新建关联记录
          writeKey: [], //1指定填写字段
          writeCorrelationKey: null, //2新建关联记录对应的关联字段
        },
        submit: {
          confirm: false, //需要二次确认 / 填写备注
          confirmConfig: {
            title: "你确认执行此操作吗？",
            content: "",
            ok: "确认",
            cancel: "取消",
            remark: false, //启用后，用户需要对操作进行备注说明
            remarkConfig: {
              name: "操作原因", //备注名称
              guidingText: "", //引导文字
              notEmpty: false, //是否允许为空
            },
          },
          password: false, //登录密码验证
        },
        submitAfterAutomation: false, //提交后继续执行自动化
        submitAfterAutomationConfig: {
          source: 1, //数据源0无，1单条，2多条
          name: null,
          automationId: newGuid(), //自动化Id
        },
        orderNo: 1, //排序号
        remark: null, //备注
        enable: 1, //启用按钮1，一直，2满足筛选条件
        enableFilter: {
          groupOp: "AND",
          rules: [],
          groups: [],
        }, //2满足筛选条件
        permission: {
          type: "all",
          view: [], //视图
        },
      },

      rules: {
        name: [
          {
            required: true,
            message: "请输入名称",
            trigger: "blur",
          },
        ],
      },

      formFieldRemark: "", //填写表单字段描述
      formCorrelationName: "",
    };
  },

  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    options: Object,
    title: {
      type: String,
    },
    mode: String,
    zeroCodeId: String,
  },
  mounted() {
    if (this.mode == "edit") {
      this.form = Object.assign(this.form, this.options);
      this.initCorrection();
      this.initAutomationDesigner();
    }
  },
  methods: {
    /**
     * 初始化自动化设计
     */
    initAutomationDesigner() {
      if (
        this.form.action == this.eipZeroCodeFormSettingButtonAction.workflow
      ) {
        findAutomationById(
          this.form.submitAfterAutomationConfig.automationId
        ).then((result) => {
          if (result.data) {
            this.form.submitAfterAutomationConfig.name = result.data.name;
            this.automationDesigner.isFreeze = result.data.isFreeze;
          }
        });
      }
    },
    /**
     * 设计
     */
    async automationDesignerClick() {
      let that = this;
      that.automationDesigner.title =
        this.form.submitAfterAutomationConfig.name;
      that.automationDesigner.visible = true;
      that.automationDesigner.configId =
        this.form.submitAfterAutomationConfig.automationId;
    },

    /**
     * 保存
     */
    automationDesignerSave() {
      let that = this;
      this.form.submitAfterAutomationConfig.name = this.form.name;
      let formData = {
        zeroCodeAutomationId:
          this.form.submitAfterAutomationConfig.automationId,
        zeroCodeId: this.zeroCodeId,
        belongToId: this.form.id,
        dataFromName: null,
        name: this.form.name,
        orderNo: 1,
        isFreeze: true,
        remark: null,
        triggerType: this.eipZeroCodeAutomationTriggerType.button,
      };
      that.$loading.show({ text: that.eipMsg.saveLoading });
      saveAutomation(formData).then(function (result) {
        that.$loading.hide();
        if (result.code === that.eipResultCode.success) {
          that.automationDesigner.title = formData.name;
          that.automationDesigner.visible = true;
          that.automationDesigner.configId = formData.zeroCodeAutomationId;

          that.initAutomationDesigner();
        }
      });
    },

    /**
     *
     * @param automationId
     */
    automationDesingerPublic(result) {
      this.form.submitAfterAutomationConfig.automationId = result.data;
      this.initAutomationDesigner();
      this.$emit("ok", this.form);
    },

    /**
     * 初始化设计器
     */
    async initCorrection() {
      let that = this;
      var nowSystemZeroCodeData = await findById(this.zeroCodeId);
      var nowColumnJson = JSON.parse(nowSystemZeroCodeData.data.columnJson);
      let zeroCodeId = this.zeroCodeId;
      if (
        this.form.form.target ==
        this.eipZeroCodeFormSettingButtonFormTarget.correlation
      ) {
        var find = that.$utils.find(
          nowColumnJson,
          (f) => f.key == this.form.form.targetCorrelationKey
        );
        if (find != null) {
          zeroCodeId = find.options.zeroCodeId;
        }
      }

      var systemZeroCodeData = await findById(zeroCodeId);
      //关联表名称
      this.formCorrelationName = systemZeroCodeData.data.name;

      if (systemZeroCodeData.data.columnJson) {
        var columnJson = JSON.parse(systemZeroCodeData.data.columnJson);
        //判断类型（填写字段）
        if (
          that.form.form.write ==
          this.eipZeroCodeFormSettingButtonFormWrite.field
        ) {
          //便利数组
          let names = [];
          this.form.form.writeKey.forEach((item) => {
            var find = that.$utils.find(columnJson, (f) => f.key == item.key);
            if (find != null) {
              names.push(find.label);
            }
          });
          that.formFieldRemark = names.join("，");
        } else {
          //新建关联
          var find = that.$utils.find(
            columnJson,
            (f) => f.key == that.form.form.writeCorrelationKey
          );
          if (find != null) {
            that.formFieldRemark = find.label;
          }
        }
      }
    },
    /**
     * 取消
     */
    formClick() {
      this.buttonForm.visible = true;
    },
    /**
     *
     */
    actionChange(e) {
      if (e.target.value == 2) {
        this.buttonForm.visible = true;
      }
    },

    /**
     * 提交操作
     */
    submitChange(e) {
      if (e.target.checked) {
        this.submitForm.visible = true;
      }
    },

    /**
     * 取消
     */
    cancel() {
      this.$emit("update:visible", false);
    },
    /**
     * 确定
     */
    ok() {
      let that = this;
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          //查询某个自动化
          that.$emit("ok", that.form);
          var automation = await findAutomationById(
            that.form.submitAfterAutomationConfig.automationId
          );
          if (
            automation.data == null &&
            that.form.action == this.eipZeroCodeFormSettingButtonAction.workflow
          ) {
            that.automationDesignerSave();
          } else {
            that.cancel();
          }
        }
      });
    },
    /**
     *图标点击
     */
    iconClick(icon) {
      this.form.icon = icon.name;
      this.form.theme = icon.theme;
    },

    /**
     * 清空图标
     */
    iconClear() {
      this.form.icon = null;
      this.form.theme = null;
    },

    /**
     *转换类型
     * @param type
     */
    convertSource(type) {
      switch (type) {
        case 0:
          return "无";
        case 1:
          return "单条";
        case 2:
          return "多条";
      }
    },

    /**
     * 表单字段
     * @param form
     */
    formOk(form) {
      this.form.form = form;
      this.initCorrection();
    },

    /**
     * 提交
     * @param form
     */
    submitOk(form) {
      this.form.submit = form;
      this.initCorrection();
    },
  },
};
</script>
<style scoped>
.filterTextCon {
  background: #f8f8f8;
  border: 1px solid #ddd;
  border-radius: 3px;
  box-sizing: border-box;
  color: #333;
  display: flex;
  padding: 6px;
  width: 100%;
}
.filterTextCon .txtFilter {
  color: #333;
  flex: 1;
  font-size: 13px;
  line-height: 24px;
}
.filterTextCon .txtFilter p .titleTxt {
  display: inline-block;
  font-size: 13px;
  line-height: 22px;
  width: 100px;
}
.Gray,
.Gray14 {
  color: #333 !important;
}
.euOtrQ {
  width: 100%;
  border: 1px solid rgb(221, 221, 221);
  border-radius: 3px;
  padding: 2px 12px 8px;
  box-sizing: border-box;
  color: rgb(51, 51, 51);
  margin: 10px 0px;
  display: flex;
  cursor: pointer;
}
.euOtrQ .txtFilter {
  flex: 1 1 0%;
  font-size: 13px;
  color: rgb(51, 51, 51);
  line-height: 20px;
  padding-left: 20px;
}
.euOtrQ .filterGroup {
  position: relative;
}

.fieldEditTxtFilter > div {
  line-height: 25px;
  width: 100%;
}
.euOtrQ .filterGroup .spliceText {
  position: absolute;
  left: -20px;
  top: -2px;
  color: rgb(117, 117, 117);
}
.euOtrQ .flexBox {
  line-height: 22px;
}
.euOtrQ .editFilter {
  color: rgb(158, 158, 158);
  font-size: 15px;
  padding-top: 5px;
}

.filterTextCon.createCon {
  background: #fff;
  display: block;
}
.Bold {
  font-weight: 700 !important;
}
.WordBreak {
  word-wrap: break-word;
  word-break: break-word;
}
</style>
